const router = require('koa-router')(),
  login=require('../models/essay1.js'),
  {con}=require('mysql2/promise'),
  log=console.log;
var moment = require('moment');

router.prefix('/login')

router.get('/essay',async function(ctx,next){
    //获取到文章的id
    const {id}=ctx.query
    let arr = [];
    let essay = await login.essay(id);
    let comment = await login.comment(id);
 
    let length = Object.keys(comment).length;
    for(let i=0;i<length;i++){  
      comment[i].time = moment(comment[i].time).format('YYYY-MM-DD ');
    }

    //改变从数据库中取出来的格式
    let publish = moment(essay[0].publish).format('YYYY-MM-DD HH:mm:ss');
    let change = moment(essay[0].change).format('YYYY-MM-DD HH:mm:ss');
    //获取到用户的id
    let userId = await login.userId(id);
    let user = await login.user(userId[0].user);
    let userImage = await login.essayImage(id);
    arr[0] = {'id':essay[0].id,
      'user':essay[0].user,
      'title':essay[0].title,
      'content':essay[0].content,
      'publish':publish,
      'change':change,
      'like':essay[0].like,
      'comment':essay[0].comment,
      'state':''
    };
    arr[1] = user;
    arr[2] = userImage;
    arr[3] = comment

    const {userID} = ctx.query;
    console.log('userID'+userID);
    let essayId = await login.likeState(userID);
    let essayLength = Object.keys(essayId).length;
    let essayArr = [];
    for(let i=0;i<essayLength;i++){
        essayArr.push(essayId[i].passageId)
    }
    length = Object.keys(arr).length;
    for(let i=0;i<length;i++){
        if(essayArr.indexOf(arr[i].id) != -1){
            arr[i].state = true;
        }else{
            arr[i].state = false;
        }
    }
    ctx.body = arr;
})


module.exports = router